/**
 * 问题：每次修改后 都需要重新执行npm run build
 * 方法一：效率低
 *    1、webpack --watch 监听代码变化，重新打包
 *    2、vscode live-server插件 or npm serve插件
 * 方法二：webpack-dev-server 效率高
 *    1、yarn add webpack-dev-server -D
 *    2、package.json script添加 webpack serve命令
 *    3、编译文件放在内存中，不会输出真实文件，快速
 */
const {resolve} = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  entry: './src',
  output: {
    filename: "js/[name].js",
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.less$/i,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2
            }
          },
          'postcss-loader',
          'less-loader'
        ],
      },
      {
        test: /\.jsx?$/i,
        use: [
            "babel-loader"
        ]
      },
      {
        test: /\.vue$/i,
        use: "vue-loader"
      }
    ]
  },

  plugins: [
    new HTMLWebpackPlugin({
      title: "Webpack App",
      template: "./public/index.html"
    }),
    new CleanWebpackPlugin(),
    new ReactRefreshWebpackPlugin(), //react实现hmr插件，但是影响build打包，仅在开发环境添加
    new VueLoaderPlugin()
  ],

  mode: 'development',
  devtool: "cheap-module-source-map",
  devServer: {
    port: 5001,
    host: 'localhost',
    open: true,
    hot: true,
    hotOnly: true,//只有HMR变化时 才更新页面，且报错并修复后，会保留报错前状态，不会刷新页面
    compress: true,
    proxy: {
      '/why': {
        target: 'https://www.baidu.com',
        pathRewrite: {
          "^/api": ''
        },
        source: false, //默认情况下，不支持没有证书https后台
        changeOrigin: true, //更改http请求头的origin，避免后台做来源校验
      },
      // historyApiFallback: true, //只要返回404，就把index.html返回
      historyApiFallback: { //详细配置
        rewrites: [
          {from: /^\/subject/, to: '/views/subject.html'},
          {from: /^\/$/, to: '/views/landing.html'},
          {from: /./, to: '/views/404.html'},
        ]
}
    }
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      '@view': resolve(__dirname, 'src/view'),
      '@asset': resolve(__dirname, 'src/asset'),
    },
    // 默认['.js', '.json', '.wasm']，如果修改 会覆盖默认
    extensions: ['.vue', '.jsx', '.ts', '.js', '.json']
  }
}